package com.satchi.struts.action.balance;

import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.satchi.hib.pojo.FinBalance;
import com.satchi.hib.pojo.FinCustomer;
import com.satchi.hib.pojo.FinUser;
import com.satchi.service.GetBalanceService;
import com.satchi.service.GetCustomerService;
import com.satchi.struts.ActionHelper;
import com.satchi.struts.form.FinBalanceForm;

public class BalanceaddAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	throws Exception {
		FinBalanceForm balanceForm = (FinBalanceForm)form;
		SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd");
		GetBalanceService gbs = new GetBalanceService();
		GetCustomerService customerServ = new GetCustomerService();
		
		FinUser fu  = gbs.runResultFin(new Object[] { balanceForm.getFinUser() });
		FinCustomer parentCustomer = customerServ.get(balanceForm.getCustomer());
		FinCustomer shop = customerServ.get(balanceForm.getShopName());
		
		FinBalance fb;
		if (balanceForm.getIsModify() == 0) {
			fb = new FinBalance();
			fb.setBalanceId(balanceForm.getBalanceId());
		} else {
			fb = gbs.get(balanceForm.getBalanceId());
		}
		
		fb.setFitmentDate(sim.parse(balanceForm.getFitmentDate()));
		fb.setWriteDate(sim.parse(balanceForm.getWriteDate()));
		fb.setCostProperty(balanceForm.getCostProperty());
		fb.setBalancePrice(balanceForm.getBalancePrice());
		fb.setShopArea(balanceForm.getShopArea());
		fb.setBalanceRemark(ActionHelper.encodeBr(balanceForm.getBalanceRemark()));
		fb.setShop(shop);
		fb.setFinCustomer(parentCustomer);
		fb.setFinUser(fu);
		fb.setIsClosed(false);
		fb.setDecorationDate(sim.parse(balanceForm.getDecorationDate()));
		gbs.save(fb);
		return mapping.findForward("success");
	}
}
